package com.ccloud.api.motorfactory.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccloud.api.motorfactory.domain.MMotorPart;
import com.ccloud.api.motorfactory.domain.MWarehouseRecord;
import com.ccloud.api.motorfactory.mapper.MWarehouseRecordMapper;
import com.ccloud.api.motorfactory.service.IMMotorPartService;
import com.ccloud.api.motorfactory.service.IMWarehouseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccloud.common.core.utils.OauthUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 出入库台账记录表 服务实现类
 * </p>
 *
 * @author chentl
 * @since 2022-04-09
 */
@Slf4j
@Service
public class MWarehouseRecordServiceImpl extends ServiceImpl<MWarehouseRecordMapper, MWarehouseRecord> implements IMWarehouseRecordService {

    @Resource
    private IMMotorPartService partService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAndSyncWarehouseSum(MWarehouseRecord warehouseRecord) {
        warehouseRecord.setCreateBy(OauthUtils.getCurrentUser().getUserId());
        warehouseRecord.setUpdateBy(OauthUtils.getCurrentUser().getUserId());

        setWarehouseSum(warehouseRecord);
        save(warehouseRecord);

        //同步库存数量
        MMotorPart toUpdate = new MMotorPart();
        toUpdate.setId(warehouseRecord.getMotorPartId());
        toUpdate.setStoreSum(warehouseRecord.getWarehouseSum());
        partService.updateById(toUpdate);
        log.info("motorPartId:{},warehouseSum:{} ,库存已同步",warehouseRecord.getMotorPartId(),warehouseRecord.getWarehouseSum());


    }

    @Override
    public IPage<MWarehouseRecord> selectPage(Page<MWarehouseRecord> page, MWarehouseRecord warehouseRecord) {
        return baseMapper.selectPage(page, warehouseRecord);
    }


    /**
     * 生成先有库存总数
     * @param warehouseRecord 库存记录
     */
    public  static void setWarehouseSum(MWarehouseRecord warehouseRecord) {
        Integer originalSum = warehouseRecord.getOriginalSum();
        Integer warehouseInNum = warehouseRecord.getWarehouseInNum();
        Integer warehouseOutNum = warehouseRecord.getWarehouseOutNum();
        if(ObjectUtil.isNotNull(originalSum) && ObjectUtil.isNotNull(warehouseInNum)){
            //计算入库后 现有库存量
            warehouseRecord.setWarehouseSum(originalSum + warehouseInNum);
        }else if(ObjectUtil.isNotNull(originalSum) && ObjectUtil.isNotNull(warehouseOutNum)){
            //计算入库后 现有库存量
            warehouseRecord.setWarehouseSum(originalSum - warehouseOutNum);
        }

    }
}
